package com.face.controller;

import com.alibaba.fastjson.JSON;
import com.face.service.AccountService;
import com.face.util.CookieUtil;
import com.face.util.StringConstans;
import com.face.util.WechatContact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class WechatGrantController {

    @Autowired
    AccountService accountService;

    @Value("${wechat.appid}")
    String appId;

    @Value("${wechat.secret}")
    String secret;

    @Value("${wechat.loginUrl}")
    private String wechatLoginUrl;

    @Value("${wechat.indexUrl}")
    private String wechatIndexUrl;

    @Value("${wechat.customerUrl}")
    private String wechatCustomerUrl;

    /**
     * 获取openid并保存在session(授权回调到该方法)
     *
     * @param code
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/grant")
    public void grantAndTurn(@RequestParam("code") String code, @RequestParam("state") String state, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String name = accountService.findUsernameByOpenid(setAndGetOpenid(request, response, code));
        if (name == null || StringUtils.isEmpty(name)) {
            response.sendRedirect(wechatLoginUrl);
            return;
        }

        choseUrl(state, response);
    }

    /**
     * 获取并设置好Openid
     *
     * @param request
     * @param response
     * @param code
     * @return
     */
    private String setAndGetOpenid(HttpServletRequest request, HttpServletResponse response, String code) {

        RestTemplate restTemplate = new RestTemplate();
        String json = restTemplate.getForObject(WechatContact.getGainOpenidURL(appId, secret, code)
                , String.class);
        Map<String, Object> map = JSON.parseObject(json, HashMap.class);

        String openid = (String) map.get("openid");
        CookieUtil.setCookie(request, response, StringConstans.WECHAT_OPENID, openid);
        return openid;
    }

    /**
     * 根据state判断并控制跳转页面
     *
     * @param state
     * @param response
     * @throws IOException
     */
    private void choseUrl(String state, HttpServletResponse response) throws IOException {

        if ("111".equals(state)) {
            response.sendRedirect(wechatIndexUrl);
            return;
        }

        if (null != state && !StringUtils.isEmpty(state) && turnToCustomer(state, response)) {
            return;
        }

        response.sendRedirect(wechatLoginUrl + "?state=313");
    }

    /**
     * 判断是否跳转到顾客详情页并进行操作
     *
     * @param state
     * @param response
     * @return
     * @throws IOException
     */
    private boolean turnToCustomer(String state, HttpServletResponse response) throws IOException {

        String[] msg = state.split("@");
        if (msg[0].equals("112") && msg.length > 1) {
            response.sendRedirect(wechatCustomerUrl + msg[1]);
            return true;
        }
        return false;
    }

}
